<template>
  <div class="department">
    <div class="department__body">
      <div class="department__body-tree-menu">
        <div class="search">
          <el-input
            v-model="keywords"
            prefix-icon="el-icon-search"
            placeholder="搜索成员或部门"
            clearable
            @change="handleSearch"
            @clear="handleSearchReset"
          >
            <template #append>
              <div>
                <el-dropdown @command="handleSearchDropdownClick">
                  <div class="search-type">
                    <span>{{ searchTypeText }} </span>
                    <i class="el-icon-arrow-down" />
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="department">部门</el-dropdown-item>
                      <el-dropdown-item command="employee">成员</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-input>
        </div>
        <el-tree
          :data="departmentList"
          :props="elTreeOptions.defaultProps"
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          :default-expanded-keys="defaultExpandedKeys"
          @node-click="handleNodeClick"
        >
          <template v-slot="{ node, data }">
            <div class="custom-tree-node">
              <span>{{ data.name }}</span>
              <el-dropdown @command="handleDropdownClick($event, data)">
                <div
                  v-show="data.id === elTreeOptions.currentNode"
                  class="custom-tree-node-button"
                >
                  <i class="el-icon-more" />
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="remove">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-tree>
        <div class="department__body-tree-menu-add-button">
          <el-button type="text" icon="el-icon-plus" @click="handleOpenDialog('create')">
            新建部门
          </el-button>
        </div>
      </div>
      <div class="demo">
        <el-divider direction="vertical" style="margin: 0;" />
      </div>
      <div class="department__body-content">
        <div class="department__body-content-header flex">
          <span class="department__name">{{ currentDepartment.name }}</span>
          <span style="color: #bbb; font-size: 14px; margin-left: 10px" class="flex items-center">
            <svg-icon icon-class="user-manger" />
            {{ currentDepartment.count }}
          </span>
        </div>

        <div class="department__body-content-table">
          <el-table
            v-loading="loading"
            :data="currentDepartEmployee"
            :header-cell-style="{background: '#F5F7FA'}"
            height="550px"
          >
            <el-table-column align="center" prop="username" label="姓名" />
            <el-table-column align="center" label="性别">
              <template v-slot="{ row }">
                <span>
                  {{ row.gender === 1 ? '男' : row.gender === 0 ? '女' : '不详' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="phone" label="手机号" />
            <el-table-column align="center" label="操作">
              <template v-slot="{ row }">
                <el-button type="text" @click="handleJumpTo(row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <el-dialog
      :visible.sync="dialogOptions.show"
      :show-close="false"
      width="300px"
      :close-on-click-modal="false"
    >
      <template #title>
        <div class="dialog-header">
          <span>{{ dialogOptions.title }}</span>
          <i class="icon el-icon-close" @click="dialogOptions.show = false" />
        </div>
      </template>
      <div class="dialog-body">
        <el-form
          ref="formRef"
          :rules="rules"
          :model="formData"
          label-width="auto"
          label-position="left"
        >
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入部门名称" />
          </el-form-item>
          <el-form-item label="部门领导">
            <el-select
              v-model="formData.leader_id"
              filterable
              placeholder="请选择部门领导"
              :filter-method="onSearchEvent"
              :loading="searchLoading"
            >
              <el-option
                v-for="(item, index) in selectOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!isParentDepartment" label="父级部门">
            <el-cascader
              v-model="formData.parent_id"
              clearable
              :options="departmentList"
              placeholder="请选择父级部门"
              :props="{ value: 'id', label: 'name', checkStrictly: true }"
            />
          </el-form-item>
          <el-form-item label="是否为父级部门">
            <el-radio-group v-model="formData.is_directory" @input="changeDepartment">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="部门描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入部门描述"
              :maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOptions.show = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addDept, editDept, delDept, numDept } from '@/api/dept'
import { getAllUser, getAllLeaders } from '@/api/v2/personnel'
import { getDept, getDeptpeople } from '@/api/v2/basic'
import { deepClone } from '@/utils'
export default {
  name: 'Department',
  data() {
    return {
      departNum: {},
      departmentList: [],
      elTreeOptions: {
        currentNode: null,
        defaultProps: {
          label: 'name',
          chidren: 'chidren'
        }
      },
      loading: false,
      currentDepartment: {
        name: '',
        count: null
      },
      currentDepartEmployee: [],
      dialogOptions: {
        show: false,
        title: '新建部门'
      },
      formData: {
        name: '',
        leader_id: null,
        parent_id: null,
        is_directory: 0,
        description: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      selectOptions: [],
      params: {
        username: '',
        // paginate: 50,
        job_status: JSON.stringify([1]),
        type: 2
      },
      searchLoading: false,
      defaultExpandedKeys: [],
      isParentDepartment: false,
      keywords: '',
      searchType: 'department'
    }
  },
  computed: {
    ...mapGetters(['defaultCompany']),
    numList() {
      const { delNum, departmentNum, oneNum } = this.departNum
      return [
        {
          label: '部门数量',
          value: departmentNum,
          icon: 'department-count',
          color: '#DA7D5D'
        }
        // {
        //   label: '父级部门',
        //   value: oneNum,
        //   icon: 'p-department-count',
        //   color: '#18BE86'
        // },
        // {
        //   label: '回收站',
        //   value: delNum,
        //   icon: 'recycle-bin',
        //   color: '#286CBD'
        // }
      ]
    },

    searchTypeText() {
      const l = {
        department: '部门',
        employee: '成员'
      }

      return l[this.searchType]
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      Promise.allSettled([
        this.getDepartNum(),
        this.getDepartmentsList(),
        // this.getDepartmentPeople(),
        this.getAllUserList(),
        this.getAllLeadersList()
      ])
      this.currentDepartment.name = this.defaultCompany.name
    },
    async getDepartNum() {
      try {
        const res = await numDept()
        this.departNum = res.data
      } catch (error) {
        console.log('error--------->', error)
      }
    },
    async getDepartmentsList(params) {
      try {
        const res = await getDept(params)
        this.departmentList = res.data.length > 0 ? res.data : []
      } catch (error) {
        this.$message.error('获取部门数据失败')
      }
    },
    async getDepartmentPeople(data) {
      this.loading = true
      try {
        const params = {
          department_id: data?.id || null,
          name: data?.name || null
        }
        const res = await getDeptpeople(params)
        console.log('res --------->', res)
        this.currentDepartEmployee = res.data
        this.currentDepartment.count = res.data.length
      } catch (error) {
        this.$message.error('部门成员获取失败')
      } finally {
        this.loading = false
      }
    },

    async getAllUserList() {
      try {
        const res = await getAllUser(this.params)
        console.log('res all User --------->', res)
        this.currentDepartEmployee = res.data
        this.currentDepartment.count = res.data.length
      } catch (error) {
        console.log('error--------->', error)
      }
    },
    async getAllLeadersList() {
      try {
        const { data } = await getAllLeaders()
        this.selectOptions =
          data.map(item => ({ label: item.username, value: item.id }))
      } catch (error) {
        console.log(error, 'getAllLeadersList')
      }
    },
    onSearchEvent(e) {
      delete this.params.user_id
      this.searchLoading = true
      this.params.username = e
      this.getAllUserList()
      this.searchLoading = false
    },

    handleNodeClick(data, node) {
      this.elTreeOptions.currentNode = data.id
      this.currentDepartment.name = data.name

      this.getDepartmentPeople({
        id: data.id
      })
    },

    async handleOpenDialog(type, data) {
      this.reset()
      if (type === 'create') {
        this.dialogOptions.title = '新建部门'
      } else {
        this.params.user_id = data.leader_id
        const a = deepClone(this.selectOptions)
        await this.getAllUserList()
        this.selectOptions = Array.from(new Set([...this.selectOptions, ...a]
          .map(JSON.stringify))).map(JSON.parse)
        this.dataEcho(data)
        this.dialogOptions.title = '修改部门'
      }
      this.dialogOptions.show = true
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },

    dataEcho(data) {
      const { id, leader_id, description, is_directory, name, parent_id } = data
      this.formData.id = id
      this.formData.leader_id = leader_id
      this.formData.description = description
      this.formData.is_directory = is_directory
      this.formData.parent_id = parent_id
      this.formData.name = name
    },

    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (!this.formData.id) {
            this.createDepartmentApi(this.formatParams(this.formData))
          } else {
            this.editDepartmentApi(this.formatParams(this.formData))
          }
        }
      })
    },

    handleDropdownClick(e, data) {
      if (e === 'edit') {
        this.handleOpenDialog('edit', data)
      } else {
        this.$confirm(
          '是否删除该部门',
          { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
        ).then(() => {
          const node = this.findParents(data.id, this.departmentList)
          if (node.parent_id) this.defaultExpandedKeys.push(node.parent_id)
          this.removeDepartmentApi({ id: data.id })
        })
      }
    },

    async removeDepartmentApi(data) {
      try {
        const res = await delDept(data)
        if (res.code === 200 || res.code === 201) {
          this.$message.success('删除成功')
          this.refresh()
          this.currentDepartment.name = this.defaultCompany.name
          await this.getDepartmentPeople()
          this.getAllUserList()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        this.$message.error('部门删除失败')
      }
    },
    formatParams(params) {
      const { parent_id, ...restParams } = params
      const data = {
        ...restParams,
        parent_id:
          Array.isArray(parent_id) ? parent_id.slice(-1)[0]
            : parent_id !== null ? parent_id : null
      }
      Object.keys(data).forEach(item => {
        if (item === null) delete data[item]
      })
      return data
    },

    async createDepartmentApi(params) {
      try {
        const res = await addDept(params)
        if (res.code >= 200 || res.code <= 299) {
          this.$message.success('部门创建成功')
          if (params.parent_id) this.defaultExpandedKeys.push(params.parent_id)
          this.refresh()
        }
      } catch (error) {
        this.$message(error.responseEnd.data.message || '部门创建失败')
      }
    },

    findParents(id, treeList) {
      for (var i = 0; i < treeList.length; i++) {
        const item = treeList[i]
        if (item.id === id) {
          return item
        }
        if (item.children && item.children.length > 0) {
          const child = this.findParents(id, item.children)
          if (child) return child
        }
      }
      return null
    },

    async editDepartmentApi(data) {
      try {
        const res = await editDept(data)
        if (res.code >= 200 || res.code <= 299) {
          this.$message.success('部门修改成功')
          this.refresh()
        }
      } catch (error) {
        this.$message(error.responseEnd.data.message || '部门修改失败')
      }
    },

    refresh() {
      this.getDepartNum()
      this.getDepartmentsList()
      // this.getDepartmentPeople()
      this.dialogOptions.show = false
    },

    reset() {
      this.formData = this.$options.data().formData
    },
    handleJumpTo(row) {
      // console.log(row,'row');
      this.$router.push({
        path: `/personnel-files/show/${row.id}`,
        query: { tag_title: row.username + '-查看', show: true }
      })
    },
    changeDepartment(val) {
      if (val === 1) {
        this.isParentDepartment = true
      } else {
        this.isParentDepartment = false
      }
      console.log(val, 'val')
    },

    handleSearchDropdownClick(e) {
      console.log('e --------->', e)
      this.searchType = e
      this.handleSearchReset()
    },

    handleSearch() {
      if (this.searchType === 'department') {
        this.getDepartmentsList({ name: this.keywords })
      } else {
        this.getDepartmentPeople({
          id: this.elTreeOptions.currentNode ?? null,
          name: this.keywords
        })
      }
    },

    handleSearchReset() {
      this.getDepartmentsList()
      this.getDepartmentPeople()
      this.keywords = ''
    }
  }
}
</script>

<style scoped lang='scss'>
.department {
  width: 100%;
  height: 90vh;
  padding: 20px;
  background-color: #fff;

  &__body {
    width: 100%;
    height: 100%;
    display: flex;
    //padding: 20px;

    .search {
      margin-bottom: 20px;

      &-type {
        cursor: pointer;
        color: #909399;
        font-size: 14px;
      }
    }

    &-tree-menu {
      padding: 0 20px 0 0;
      width: 20%;
      overflow-y: auto;
      &-add-button {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
      .custom-tree-node {
        cursor: default;
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
        //display: flex;
        &-button {
          width: 18px;
          height: 18px;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #E8E8E8;
          border-radius: 2px;
          font-size: 12px;
          color: #C0C4CC;
        }
      }
    }
    &-content {
      //flex: 1;
      width: 80%;
      padding: 0 0 0 20px;
      &-header {
        margin-bottom: 10px;
        .department__name {
          font-weight: bold;
        }
      }
    }
  }
  .dialog-header {
    font-size: 24px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #DCDFE6;
    padding: 20px;
    .icon {
      color: #8E8E8E;
    }
  }
  .dialog-footer {
    padding: 20px;
    border-top: 1px solid #DCDFE6;
  }
}
:deep(.el-dialog__header) {
  padding: 0;
}
:deep(.el-dialog__footer) {
  padding: 0;
}
.demo .el-divider--vertical{
  display:inline-block;
  width:1px;
  height:100%;
  margin:0 8px;
  vertical-align:middle;
  position:relative;
}

::v-deep(.el-tree-node__content) {
  height: auto;
  padding: 10px;
  border-radius: 4px;
}

::v-deep(.el-tree--highlight-current) {
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #F5F5F5;
  }
}

::v-deep(.el-divider--vertical) {
  margin: 0 !important;
}
</style>
